package com.h4313.ghome.ui.fragments;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;

import com.h4313.ghome.GHomeApplication;
import com.h4313.ghome.R;
import com.h4313.ghome.io.AvailableSourcesTask;
import com.h4313.ghome.io.AvailableSourcesTask.AvailableSourcesCallback;
import com.h4313.ghome.model.Capteur;
import com.h4313.ghome.ui.NewModuleCreation;
import com.h4313.ghome.ui.adapters.CapteursAdapter;

public class CreateSecurityFragment extends Fragment implements AvailableSourcesCallback {

	protected EditText mEditTempSeuil;
	protected TextView mTvWarningTempSeuil;
	protected Button mBtnTempSeuil;
	protected boolean warning;
	
	private NewModuleCreation mCreation;

	final static Integer TEMP_SEUIL_MAX = 50;
	final static Integer TEMP_SEUIL_MIN = 5;

	private final static String MODULE_NAME = "name";

	private MenuItem mMenuItem;
	private Spinner mSpinnerContact;
	private Spinner mSpinnerSwitch;
	private ProgressBar mWait;

	public static CreateSecurityFragment newInstance(String name) {
		CreateSecurityFragment frag = new CreateSecurityFragment();
		Bundle bundle = new Bundle();
		bundle.putString(MODULE_NAME, name);
		frag.setArguments(bundle);
		return frag;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View v = inflater.inflate(R.layout.fragment_create_security, container,
				false);

		mSpinnerContact = (Spinner) v.findViewById(R.id.required_contact);
		mSpinnerContact.setEnabled(false);
		mSpinnerSwitch = (Spinner) v.findViewById(R.id.required_switch);
		mSpinnerSwitch.setEnabled(false);
		mWait = (ProgressBar) v.findViewById(R.id.sp_wait);

		return v;
	}
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);

		if (!(activity instanceof NewModuleCreation)) {
			throw new RuntimeException(
					"activity must implement NewModuleCreation");
		} else {
			mCreation = (NewModuleCreation) activity;
		}
	}
	
	@Override
	public void onStart() {
		super.onStart();
		AvailableSourcesTask task = new AvailableSourcesTask(this,
				getActivity());
		String moduleName = getArguments().getString(MODULE_NAME);
		task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, GHomeApplication.SERVER_URL + "/modules/" + moduleName
				+ "/sources");
	}
	
	@Override
	public void onAvailableSourcesFound(HashMap<String, List<Capteur>> capteurs) {
		if (getActivity() == null || isDetached()) {
			return;
		}
		
		// remove the progressBar for data has been retrieved...
		mWait.setVisibility(View.GONE);
		// ...and then process the data
		for (String type : capteurs.keySet()) {
			if ("contact".equals(type) || "switch".equals(type)) {
				List<Capteur> l = capteurs.get(type);
				if (l.isEmpty()) {
					// no capteur is available for the specified
					// type. A pop-up is shown, advising the
					// user
					AlertDialog.Builder builder = new AlertDialog.Builder(
							getActivity());
					builder.setPositiveButton("OK",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// nothing to do. User
									// clicked "OK", OK ?
								}
							});
					builder.setMessage(String.format(
							getResources().getString(
									R.string.no_capteur_available), type));
					builder.setTitle(R.string.no_capteur_available_title);
					builder.create().show();
				} else {
					if ("contact".equals(type)) {
						mSpinnerContact.setEnabled(true);
						mSpinnerContact.setAdapter(new CapteursAdapter(getActivity(), l));
						if (mSpinnerSwitch.isEnabled()) {
							//both capteurs has been set
							mMenuItem.setEnabled(true);
						}
					} else if ("switch".equals(type)) {
						mSpinnerSwitch.setEnabled(true);
						mSpinnerSwitch.setAdapter(new CapteursAdapter(getActivity(), l));
						if (mSpinnerContact.isEnabled()) {
							//both capteurs has been set
							mMenuItem.setEnabled(true);
						}
					}
				}
			}
		}
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.fragment_create_morning_conf, menu);
		mMenuItem = menu.findItem(R.id.menu_create_morning_conf);
		mMenuItem.setEnabled(false);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.menu_create_morning_conf) {
			
			addModule();
			
			return true;
		} else {
			return super.onOptionsItemSelected(item);
		}
	}
	
	private void addModule () {
		
		Map<String, String> params = new HashMap<String, String>();
		
		params.put("contact", String.valueOf(((Capteur) mSpinnerContact
				.getSelectedItem()).getIdCapteur()));
		
		params.put("switch", String.valueOf(((Capteur) mSpinnerSwitch
				.getSelectedItem()).getIdCapteur()));
		
		mCreation.createModule(getArguments().getString(MODULE_NAME), params);
	}
}
